package edu.nf.project.services.accountsAndPermissions.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.nf.project.entitys.entity.accountsAndPermissions.convention.Users;
import edu.nf.project.entitys.entity.accountsAndPermissions.relevancy.Users_Roles;
import edu.nf.project.entitys.enums.accountsAndPermissions.UsersStatusEnum;
import edu.nf.project.mappers.accountsAndPermissions.convention.UsersMapper;
import edu.nf.project.mappers.accountsAndPermissions.relevancy.Users_RolesMapper;
import edu.nf.project.mappers.employeeAndCustomerInformation.convention.CustomerInfoMapper;
import edu.nf.project.services.accountsAndPermissions.UsersService;
import edu.nf.project.services.exception.derivedAnomalies.UsersException;
import edu.nf.project.utils.SHA256Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 账户信息 Service 实现类
 */
@Service
public class UsersServiceImpl implements UsersService {
    /**
     * Users映射实例
     */
    @Autowired
    private UsersMapper usersMapper;

    /**
     * CustomerInfo映射实例
     */
    @Autowired
    private CustomerInfoMapper customerInfoMapper;

    @Autowired
    private Users_RolesMapper users_rolesMapper;

    /**
     * 登录
     * @param phone 电话号码
     * @param pwd 密码
     * @return 用户信息
     */
    @Override
    public Users login(String phone, String pwd) {
        // 使用 LambdaQueryWrapper 构建查询条件
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        // eq：添加一个等值条件
        // Users::getPwd, pwd      ：Users 的 getPwd 方法的值等于 pwd
        wrapper.eq(Users::getPhone, phone)
               .eq(Users::getPwd, SHA256Util.encrypt(pwd));
        // 存在结果就返回 Users 对象
        return usersMapper.selectOne(wrapper);
    }

    /**
     * 注册
     * @param user 用户信息
     * @return 是否成功
     */
    @Override
    public boolean register(Users user) {
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        // Users::getPhone, user.getPhone()  ：Users 的 getPhone 方法的值等于 user.getPhone()
        wrapper.eq(Users::getPhone, user.getPhone());
        // 若手机号存在则返回 false
        if (usersMapper.selectCount(wrapper) > 0) {
            return false;
        }
        // 否则添加新用户对象，若插入成功则返回 true
        return usersMapper.insert(user) > 0;
    }

    /**
     * 获取用户信息
     * @param userId 用户ID
     * @return 用户信息
     */
    @Override
    public Users getUserInfo(Integer userId) {
        // 按用户ID返回用户信息
        return usersMapper.selectById(userId);
    }

    /**
     * 更新用户信息
     * @param user 用户信息
     * @return 是否成功
     */
    @Override
    public boolean updateUser(Users user) {
        // 检查是否存在新手机号
        if (StringUtils.hasText(user.getPhone())) {
            LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
            // 检查手机号与ID是否各自相等
            wrapper.eq(Users::getPhone, user.getPhone())
                    .ne(Users::getUId, user.getUId());
            // 若新手机号已存在则返回false
            if (usersMapper.selectCount(wrapper) > 0) {
                return false;
            }
        }
        // 只要密码不为空，直接覆盖（前端已加密）
        // 无需再加密和比对
        // 否则更新用户信息，成功则返回true
        return usersMapper.updateById(user) > 0;
    }

    /**
     * 分页查询用户列表
     * @param page 分页参数
     * @param uName 昵称（可选）
     * @param phone 手机号（可选）
     * @return 分页结果
     */
    @Override
    public Page<Users> getUserList(Page<Users> page, String uName, String phone) {
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        // 若存在昵称，则加入昵称匹配
        if (StringUtils.hasText(uName)) {
            wrapper.like(Users::getUName, uName);
        }
        // 若存在电话，则加入电话匹配
        if (StringUtils.hasText(phone)) {
            wrapper.like(Users::getPhone, phone);
        }
        // 按创建时间降序排序
        wrapper.orderByDesc(Users::getCreatedAt);
        // 返回分页结果
        return usersMapper.selectPage(page, wrapper);
    }

    @Override
    public List<Users> getAllUsers() {
        return usersMapper.selectList(null);
    }

    @Override
    public List<Users> getUsersByTimeRange(Date startTime, Date endTime, String uName) {
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();

        // 处理开始时间
        if (startTime != null) {
            Calendar startCal = Calendar.getInstance();
            startCal.setTime(startTime);
            startCal.set(Calendar.HOUR_OF_DAY, 0);
            startCal.set(Calendar.MINUTE, 0);
            startCal.set(Calendar.SECOND, 0);
            startCal.set(Calendar.MILLISECOND, 0);
            queryWrapper.ge(Users::getCreatedAt, startCal.getTime());
        }

        // 处理结束时间
        if (endTime != null) {
            Calendar endCal = Calendar.getInstance();
            endCal.setTime(endTime);
            endCal.set(Calendar.HOUR_OF_DAY, 23);
            endCal.set(Calendar.MINUTE, 59);
            endCal.set(Calendar.SECOND, 59);
            endCal.set(Calendar.MILLISECOND, 999);
            queryWrapper.le(Users::getCreatedAt, endCal.getTime());
        }

        // 添加用户名模糊查询条件（如果提供了用户名）
        if (StringUtils.hasText(uName)) {
            queryWrapper.like(Users::getUName, uName);
        }

        // 按创建时间降序排序
        queryWrapper.orderByDesc(Users::getCreatedAt);

        List<Users> result = usersMapper.selectList(queryWrapper);

        return result;
    }

    @Override
    @Transactional
    public boolean delUsers(Integer[] userIds) {
        if (userIds == null || userIds.length == 0) {
            return false;
        }

        // 创建一个 Users 对象，设置 usersStatus 为 DELETED
        Users userToUpdate = new Users();
        userToUpdate.setUsersStatus(UsersStatusEnum.DELETED);

        // 创建一个 LambdaQueryWrapper，用于指定需要更新的用户ID
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Users::getUId, (Object[]) userIds);

        // 批量更新用户状态
        int result = usersMapper.update(userToUpdate, queryWrapper);

        // 返回更新的数量是否大于0
        return result > 0;
    }

    @Override
    public boolean isCustomer(Integer userId) {
        LambdaQueryWrapper<Users_Roles> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users_Roles::getUId, userId).ne(Users_Roles::getRId,"3");
        Users_Roles ur = users_rolesMapper.selectOne(queryWrapper);
        return ur != null;
    }

    @Override
    public boolean verifyPassword(String uId, String pwd) {
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Users::getUId, uId);
        Users user = usersMapper.selectOne(wrapper);
        Boolean verify = SHA256Util.verify(pwd, user.getPwd());
        if (!verify) {
            throw new UsersException(10007, "密码与原密码不匹配");
        }
        return verify;
    }
}
